/**
 * Description
 *
 * Creation Date 02/11/2017
 * @author Candy
 */
'use strict';
import TopBrandsModel from '../models/top-brands';
import cheerio from 'cheerio'
import superagent from 'superagent'

class TopBrand {
	constructor() {}
	async getTopBrands(req, res, next) {
		superagent.get('https://www.visiondirect.com.au/')
			.end(async(err, ares) => {
				if (err) {
					console.log(err);
					return;
				}
				try {
					const $ = cheerio.load(ares.text);
					let name ='',
						id = 0,
						image = '';
					let elements = $('#menuN_level_1 #top_sun_glass_list ul li');
					for (let i = 0; i<elements.length; i++) {
						let hrefArr = $(elements[i]).find('a').attr('href').split('/')
						name = hrefArr[hrefArr.length - 2];
						name = name.replace(/-/g, ' ');
						image = $(elements[i]).find('img').attr('src');
						const hadbrandInfo = await TopBrandsModel.findOne({brand_name: name, brand_image: image}, '-_id');
						if(!hadbrandInfo) {
							id += 1;
							await TopBrandsModel.create({brand_id: id, brand_name: name, brand_image: image})
						}
					}
					const brandData = await TopBrandsModel.find({}, '-_id');
					res.send({
						status: 1,
						data: brandData
					})
				} catch (err) {
					console.log('Error', err)
					throw new Error(err)
				}
			});
	}
}

export default new TopBrand()

